"""
数据库部分
"""
import pymysql
import hashlib


class Dict:
    def __init__(self):
        self.db = pymysql.connect(
            host="127.0.0.1",
            port=3306,
            user='root',
            password='123456',
            database='db_school',
            charset='utf8'
        )
        self.cur = self.db.cursor()

    def do_register(self, user, passwd):
        passwd = Dict.change_pwd(passwd)
        try:
            sql = 'insert into user(name,password)' \
                  'values (%s,%s);'
            self.cur.execute(sql, [user, passwd])
        except Exception as e:
            print(e)
            self.db.rollback()
            return False
        else:
            self.db.commit()
            return True

    def do_login(self, user, passwd):
        passwd = Dict.change_pwd(passwd)
        sql = 'select * from user where ' \
              'name=%s and password=%s;'
        self.cur.execute(sql, [user, passwd])
        if self.cur.fetchone():
            return True
        else:
            return False

    def do_queryword(self, word):
        sql = 'select mean from words where word = %s;'
        self.cur.execute(sql, [word])
        return self.cur.fetchone()

    def close(self):
        self.cur.close()
        self.db.close()

    # 数据表操作

    @staticmethod
    def change_pwd(pwd):
        hash = hashlib.md5()
        hash.update(pwd.encode())
        return hash.hexdigest()
